import React, {Component} from "react";
import Realm from "realm";

/**
 * realm数据库的简单封装类
 * Created by 10691 on 17/5/16.
 */

// 首页各个字段
const HomeSchema = {
    name: 'HomeData',
    primaryKey: 'id',
    properties: {
        id: 'int',
        title: 'string',
        image: 'string',
        mall: 'string',
        pubtime: 'string',
        fromsite: 'string',
    }
};

// 海淘各个字段
const HaiTaoSchema = {
    name: 'HaiTaoData',
    properties: {
        id: 'int',
        title: 'string',
        image: 'string',
        mall: 'string',
        pubtime: 'string',
        fromsite: 'string',
    },
};

// 小时风云榜各个字段
const HourListSchema = {
    name: 'HourListData',
    properties: {
        id: 'int',
        title: 'string',
        image: 'string',
        mall: 'string',
        pubtime: 'string',
        fromsite: 'string',
    },
};

// 初始化realm
let realm = new Realm({schema: [HomeSchema, HaiTaoSchema, HourListSchema]});

export default class RealmUtil extends Component {

    /**
     * 添加数据
     * @param schema 要添加到的数据表
     * @param data 要添加的数据
     */
    static create(schema, data) {
        realm.write(() => {
            for (let i = 0; i < data.length; i++) {
                realm.create(schema, {
                    id: data[i].id,
                    title: data[i].title,
                    image: data[i].image,
                    mall: data[i].mall,
                    pubtime: data[i].pubtime,
                    fromsite: data[i].fromsite
                })
            }
        });
    }

    /**
     * 查询所有数据
     * @param schema 要查询的数据表
     * @returns {*}
     */
    static loadAll(schema) {
        return realm.objects(schema);
    }

    /**
     * 删除所有数据
     * @param schema 要删除的数据表
     */
    static removeAllData(schema) {
        realm.write(() => {
            // 删除对象表
            realm.delete(realm.objects(schema))
        })
    }

    /**
     * 条件查询
     * @param schema 要查询的数据表
     * @param filtered 查询条件
     */
    static filtered(schema, filtered) {
        // 获取筛选对象
        let object = realm.objects(schema).filtered(filtered);

        return object ? object : '未找到数据';
    }

}